package com.uama.audio.util;

import android.support.annotation.NonNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author wenhu Tong
 * @email wenhu.tong@uama.com.cn
 * @date 2017/11/7 13:39
 * @desc
 */
public class FileUtil {

    public static boolean reNameFile(@NonNull String sourcePath, @NonNull String targetPath) {
        boolean isSuccess = false;
        File file = new File(sourcePath);
        if (!file.exists()) {
            return isSuccess;
        }

        File target = new File(targetPath);
        if (!target.getParentFile().exists()) {
            target.getParentFile().mkdirs();
        }

        try {
            isSuccess = file.renameTo(new File(targetPath));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return isSuccess;
    }

    public static boolean deleteFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }

    public static boolean isFileExist(String path) {
        File file = new File(path);
        return file.exists();
    }

    public static void mkParentDir(String path) {
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }
    }

    public static void mkDir(String path){
        File file = new File(path);
        if(!file.exists()){
            file.mkdir();
        }
    }

    public static void copy(String sourcePath, String targetPath) throws IOException {
        File target = new File(targetPath);
        if (!target.getParentFile().exists()) {
            target.getParentFile().mkdirs();
        }

        FileInputStream fis = new FileInputStream(new File(sourcePath));
        FileOutputStream fos = new FileOutputStream(new File(targetPath));
        byte[] buffer = new byte[2048];
        int count;
        while ((count = fis.read(buffer)) != -1) {
            fos.write(buffer, 0, count);
        }
        fos.flush();
        fos.close();
        fis.close();

    }
}
